import { PositionMap, Sizer } from "../type";
import { SVGElement } from "../typeSC";

export default class SVGSizer implements Sizer {
    width: number = 0;
    height: number = 0;

    positionMap: PositionMap = {};

    constructor(svgElementMatrix: SVGElement[][]) {
        const widthBlocks: number[] = [];
        const heightBlocks: number[] = [];

        for (let svgElementHorizontal of svgElementMatrix) {
            const widthElements: number[] = [];
            const heightElements: number[] = [];

            for (let svgElement of svgElementHorizontal) {
                const x = svgElement.margin.left + this.sumArray(widthElements);
                const y = svgElement.margin.top + this.sumArray(heightBlocks);

                const elementWidth = svgElement.margin.left + svgElement.margin.right + svgElement.width;
                const elementHeight = svgElement.margin.top + svgElement.margin.bottom + svgElement.height;

                widthElements.push(elementWidth);
                heightElements.push(elementHeight);

                this.positionMap[svgElement.id] = { x, y }; 
            }

            const blockWidth = this.sumArray(widthElements);
            const blockHeight = Math.max(...heightElements);

            widthBlocks.push(blockWidth);
            heightBlocks.push(blockHeight);
        }

        this.width = Math.max(...widthBlocks);
        this.height = this.sumArray(heightBlocks);
    }

    public getPosition(id: string) {
        return this.positionMap[id] ?? null;
    }

    private sumArray(arr: number[]): number {
        return arr.reduce((acc: number, value: number) => acc += value, 0);
    }
}